/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef IMAGE_KNIFE_C_TASK_WORKER_H
#define IMAGE_KNIFE_C_TASK_WORKER_H

#include "napi/native_api.h"
#include "imageknife_task_internal.h"
#include <string>
#include <thread>


namespace ImageKnifeC {
typedef std::function<void(std::shared_ptr<ImageKnifeTaskInternal> task)> AsyncTask;
typedef std::function<void(void *data)> AsyncFunc;
typedef std::function<void(void *data, napi_deferred deferred)> AsyncComplete;

class TaskWorker {
public:
    static TaskWorker *GetInstance()
    {
        static TaskWorker taskWorker;
        return &taskWorker;
    }
    
    // 纯C用法也得调用这个接口
    void SetEnv(napi_env env)
    {
        if (env_ == nullptr) {
            env_ = env;
            PrepareThreadsafeFunc();

            mainThreadId_ = std::this_thread::get_id();
        }
    }

    // 成功返回promise，失败返回nullptr
    // 如果调用线程不是主线程则返回promise无意义，也会返回nullptr
    // taskInfo用于描述任务信息，在发生错误时该信息也会附加至日志上
    napi_value PushTask(AsyncFunc execute, AsyncComplete complete, void *data,
                        std::string taskInfo, napi_qos_t qos = napi_qos_default);

    // 返回true表示成功从主线程开启了任务
    bool PushTask(AsyncTask execute, AsyncTask complete, std::shared_ptr<ImageKnifeTaskInternal> task,
                  napi_qos_t qos = napi_qos_default);

private:
    class InnerWorker {
    public:
        napi_async_work work;
        napi_deferred deferred_;
        napi_qos_t qos = napi_qos_default;
        std::string taskInfo;

        std::shared_ptr<ImageKnifeTaskInternal> task = nullptr;
        AsyncTask executeTask = nullptr;
        AsyncTask completeTask = nullptr;

        void *data = nullptr;
        AsyncFunc execute = nullptr;
        AsyncComplete complete = nullptr;

        static void ExecuteCallback(napi_env env, void *data)
        {
            InnerWorker* worker = static_cast<InnerWorker*>(data);
            if (worker->executeTask != nullptr) {
                worker->executeTask(worker->task);
            } else if (worker->execute != nullptr) {
                worker->execute(worker->data);
            }
        }

        static void CompleteCallback(napi_env env, napi_status status, void *data)
        {
            InnerWorker* worker = static_cast<InnerWorker*>(data);
            if (status != napi_cancelled) {
                if (worker->completeTask != nullptr) {
                    worker->completeTask(worker->task);
                } else if (worker->complete != nullptr) {
                    worker->complete(worker->data, worker->deferred_);
                }
            }

            napi_delete_async_work(env, worker->work);
            delete worker;
        }
    };

    std::thread::id mainThreadId_;
    napi_env env_ = nullptr;
    napi_threadsafe_function threadsafeFunc_ = nullptr;

    napi_value QueueWork(InnerWorker *worker);

    void QueueWorkThreadsafe(InnerWorker *worker);

    static void CallJsCallback(napi_env env, napi_value jsCallback, void *context, void* data);

    void PrepareThreadsafeFunc();

    ~TaskWorker()
    {
        if (threadsafeFunc_ != nullptr) {
            napi_release_threadsafe_function(threadsafeFunc_, napi_tsfn_release);
        }
    }
};

} // end of namespace

#endif // IMAGE_KNIFE_C_TASK_WORKER_H
